<template>
	<view>
		<view class="title">
			<u-icon name="kefu-ermai"></u-icon>
			<text>客服在线列表</text>
		</view>
		
		<view v-for="(item, index) in onLine.adminSet" @click="toPage(item)">
			<view class="onLineItem">
				<view class="onLineItem-left">
					<u-icon name="account-fill"></u-icon>
					<text>{{ item }} </text>
				</view>
				
				<u-icon name="arrow-rightward"></u-icon>
			</view>
		</view>
		
		<view v-if="adminSetLength == 0">
			<view>抱歉暂无客服在线</view>
		</view>
		
		<!-- <button @click="socketOnsend('user->json', 'a_1')">测试</button> -->
	</view>
</template>

<script>
	import { mapState } from 'vuex'
	
	export default {
		data() {
			return {
				socket: '',
				msg: [],
				onLine: '',
			}
		},
		computed: {
			...mapState('user', ['userId']),
			adminSetLength() {
				if (typeof this.onLine.adminSet === 'undefined') {
					return 0
				}
				return this.onLine.adminSet.length
			}
		},
		methods: {
			initSocket() {
				this.socket = new WebSocket('ws://localhost:8080/socket/u_' + this.userId)
				this.socket.onopen = this.socketOnOpen
				this.socket.onclose = this.socketOnClose
				this.socket.onerror = this.socketOnError
				this.socket.onmessage = this.socketOnMessage
			},
			socketOnOpen() {
				console.log('建立连接')
			},
			socketOnClose() {
				console.log('关闭连接')
				this.socket.close() 
			},
			socketOnError(e) {
				console.log('连接出现异常', e)
			},
			socketOnMessage(o) {
				const {msg, isSave} = JSON.parse(o.data)
				
				if (isSave) {
					this.msg.push(msg)
				} else {
					this.onLine = JSON.parse(msg)
				}
				
				console.log(msg)
			}, 
			socketOnsend(msg, toId) {
				this.socket.send( JSON.stringify({msg, toId}) )
			},
			toPage(item) {
				uni.navigateTo({
					url: '/pages/dialogue/dialogue'
				})
			}
		},
		created() {
			this.initSocket()
		},
		destroyed() {
			this.socket.onclose();
		}
	}
</script>

<style>
	.title{
		font-size: 20px;
		padding: 25rpx;
	}
	
	.title text{
		margin-left: 20rpx;
	}
	
	.onLineItem{
		display: flex;
		justify-content: space-between;
		background-color: #FFFFFF;
		padding: 20rpx 30rpx;
		border-radius: 17px;
		font-size: 18px;
		margin: 10rpx;
		box-shadow: rgba(60, 64, 67, 0.3) 0px 1px 2px 0px,
					rgba(60, 64, 67, 0.15) 0px 2px 6px 2px;
	}
	
	.onLineItem-left{
		display: flex;
	}
	
	.onLineItem-left text{
		margin-bottom: 8rpx;
		margin-left: 20rpx;
	}
</style>
